package com.CampusForum.community.controller;


import com.CampusForum.community.entity.Message;
import com.CampusForum.community.entity.Page;
import com.CampusForum.community.entity.User;
import com.CampusForum.community.service.MessageService;
import com.CampusForum.community.service.UserService;
import com.CampusForum.community.util.CommunityUtil;
import com.CampusForum.community.util.HostHolder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@Slf4j
public class MessageController {
    @Autowired
    private MessageService messageService;
    @Autowired
    private UserService userService;
    @Autowired
    private HostHolder hostHolder;

    @GetMapping("/letter/list")
    public String getPrivateMessages(Model model, Page page) {
        User user = hostHolder.getUser();
        int rows = messageService.getTotalRows(user.getId());
        // 设置分页信息
        page.setPath("/letter/list");
        page.setLimit(5);
        page.setRows(rows);
        // 获取该用户的这一页的所有会话
        List<Message> messageList = messageService.getConversations(user.getId(), page.getOffset(), page.getLimit());
        if (messageList == null) {
            log.info("没有会话");
            return "/site/letter";
        }
//        System.out.println("messageList.toString() = " + messageList.toString());
        List<Map<String, Object>> mapList = new ArrayList<>();
        for (Message message : messageList) {
            Map<String, Object> map = new HashMap<>();
            map.put("unreadCount", messageService.getLetterUnreadCount(user.getId(),
                    message.getConversationId()));
            int targetId = user.getId() == message.getFromId() ? message.getToId() : message.getFromId();
            map.put("target", userService.getUserById(targetId));
            map.put("conversation", message);
            map.put("letterCount", messageService.getLetterCount(message.getConversationId()));
            mapList.add(map);
        }
        model.addAttribute("conversations", mapList);
        int letterUnreadCount = messageService.getLetterUnreadCount(user.getId(), null);
        model.addAttribute("letterUnreadCount", letterUnreadCount);
        return "/site/letter";
    }

    /**
     * 获取会话详情信息
     */
    @GetMapping("/letter/detail/{conversationId}")
    public String getSessionDetails(Model model, Page page,
                                    @PathVariable("conversationId") String conversationId) {
        page.setLimit(5);
        // 获取这次会话中的所有消息的数量
        page.setRows(messageService.getLetterCount(conversationId));
        page.setPath("/letter/detail/" + conversationId);
        model.addAttribute("target", getChatUser(conversationId));
        // 获取当前对话的所有消息
        List<Message> conversations = messageService.getLetters(conversationId, page.getOffset(), page.getLimit());
        if (conversations == null) {
            return "/site/letter-detail";
        }
        List<Map<String, Object>> letters = new ArrayList<>();
        for (Message message : conversations) {
            Map<String, Object> map = new HashMap<>();
            User fromUser = userService.getUserById(message.getFromId());
            map.put("fromUser", fromUser);
            map.put("letter", message);
            letters.add(map);
        }
        model.addAttribute("letters", letters);

        // 设置消息已读
        List ids = new ArrayList();
        for (Message message : conversations){
            if (message.getToId() == hostHolder.getUser().getId() && message.getStatus() == 0) {
                ids.add(message.getId());
            }
        }
        // messageService.
        return "/site/letter-detail";
    }

    /**
     * 获取会话对象
     */
    private User getChatUser(String conversationId) {
        String[] ids = conversationId.split("_");
        int id0 = Integer.parseInt(ids[0]);
        int id1 = Integer.parseInt(ids[1]);
        User user = hostHolder.getUser();
        int targetId = user.getId() == id0 ? id1 : id0;
        User target = userService.getUserById(targetId);
        return target;
    }

    @PostMapping("/letter/send")
    @ResponseBody
    public String sendMessage(String toName, String content) {
        // 查询用户存不存在
        User toUser = userService.getUserByName(toName);
        if (toUser == null) {
            return CommunityUtil.getJSONString(1, "发送对象不存在");
        }
        // 消息存入数据库
        int code = messageService.insertMessage(toUser.getId(), content);
        if (code == 1) return  CommunityUtil.getJSONString(0);
        return CommunityUtil.getJSONString(1, "插入对象失败");
    }

}
